/**
 * 签署位工具函数
 */
import _ from 'lodash'
import signPositionConst from '../constant/signPosition'

/**
 * 防抖函数
 * @param {Function} fn 需要防抖的函数
 * @param {Number} delay 延迟时间
 */
export const debounce = (fn, delay) => {
  let timer = null
  return function() {
    const context = this
    const args = arguments
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(context, args)
    }, delay)
  }
}

/**
 * 批量添加签章
 * @param {Object} params 批量添加参数
 */
export const addMultiSign = (params) => {
  const { showSignature, showDate, direction, positions, signs } = params
  const siteInfos = []
  
  // 遍历关键字位置
  positions.forEach((position, index) => {
    const { page, posx, posy } = position
    
    // 遍历选中的签章
    signs.forEach((sign, signIndex) => {
      const { person, signMethod } = sign
      const sealSize = getSealSize(signMethod)
      
      // 计算位置偏移
      let offsetX = 0
      let offsetY = 0
      
      if (direction === signPositionConst.directionMap.horizontal) {
        // 水平排列
        offsetX = signIndex * (sealSize.width + 10)
      } else {
        // 垂直排列
        offsetY = signIndex * (sealSize.height + 10)
      }
      
      // 创建签章信息
      const siteInfo = {
        siteId: generateUUID(),
        page,
        posx: posx + offsetX,
        posy: posy + offsetY,
        width: sealSize.width,
        height: sealSize.height,
        signMethod,
        signSubjectId: person.id,
        showSignature,
        showDate
      }
      
      siteInfos.push(siteInfo)
    })
  })
  
  return siteInfos
}

/**
 * 获取签章尺寸
 * @param {Number} signMethod 签章类型
 */
export const getSealSize = (signMethod) => {
  switch (signMethod) {
    case signPositionConst._signNoMap.public:
      return signPositionConst.sealSize.public
    case signPositionConst._signNoMap.ones:
      return signPositionConst.sealSize.ones
    case signPositionConst._signNoMap.cwz:
      return signPositionConst.sealSize.cwz
    case signPositionConst._signNoMap.qz:
    case signPositionConst._signNoMap.frqz:
    default:
      return signPositionConst.sealSize.qz
  }
}

/**
 * 获取签章颜色
 * @param {Number} signMethod 签章类型
 */
export const getSealColor = (signMethod) => {
  switch (signMethod) {
    case signPositionConst._signNoMap.public:
      return signPositionConst.sealColor.public
    case signPositionConst._signNoMap.ones:
      return signPositionConst.sealColor.ones
    case signPositionConst._signNoMap.cwz:
      return signPositionConst.sealColor.cwz
    case signPositionConst._signNoMap.qz:
    case signPositionConst._signNoMap.frqz:
    default:
      return signPositionConst.sealColor.qz
  }
}

/**
 * 重置签章位置
 * @param {Object} sign 签章信息
 * @param {Object} pdfInfo PDF信息
 */
export const resetPosition = (sign, pdfInfo) => {
  console.log(pdfInfo,'pdfInfo')
  if (!sign) {
    return
  }
  const { divWidth, divHeight, docNumPages } = pdfInfo
  const { page, posx, posy, width, height } = sign
  
  // 检查是否超出页面边界
  let newPage = page
  let newPosx = posx
  let newPosy = posy
  
  // 检查X轴边界
  if (newPosx < 0) {
    newPosx = 0
  } else if (newPosx + width > divWidth) {
    newPosx = divWidth - width
  }
  
  // 检查Y轴边界
  if (newPosy < 0) {
    newPosy = 0
  } else if (newPosy + height > divHeight) {
    // 如果超出底部边界，检查是否有下一页
    if (newPage < docNumPages) {
      newPage += 1
      newPosy = 0
    } else {
      newPosy = divHeight - height
    }
  }
  
  return { ...sign, page: newPage, posx: newPosx, posy: newPosy }
}

/**
 * 生成UUID
 */
export const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

/**
 * 处理签章拖拽
 * @param {Object} options 拖拽选项
 */
export const handleDown = (options) => {
  const { person, event, signMethod, pdfElt, dragTemp, signs, callback } = options
  
  // 获取签章尺寸
  const sealSize = getSealSize(signMethod)
  
  // 创建临时拖拽元素
  const dragElt = document.createElement('div')
  dragElt.className = 'sign-drag-temp'
  dragElt.style.width = `${sealSize.width}px`
  dragElt.style.height = `${sealSize.height}px`
  dragElt.style.backgroundColor = getSealColor(signMethod)
  dragElt.style.position = 'absolute'
  dragElt.style.zIndex = '9999'
  dragElt.style.opacity = '0.7'
  dragElt.style.cursor = 'move'
  
  // 设置初始位置
  dragElt.style.left = `${event.clientX - sealSize.width / 2}px`
  dragElt.style.top = `${event.clientY - sealSize.height / 2}px`
  
  // 添加到body作为临时容器
  document.body.appendChild(dragElt)
  
  // 鼠标移动事件
  const handleMove = (moveEvent) => {
    dragElt.style.left = `${moveEvent.clientX - sealSize.width / 2}px`
    dragElt.style.top = `${moveEvent.clientY - sealSize.height / 2}px`
  }
  
  // 鼠标释放事件
  const handleUp = (upEvent) => {
    // 移除事件监听
    document.removeEventListener('mousemove', handleMove)
    document.removeEventListener('mouseup', handleUp)
    
    // 获取PDF元素位置和滚动偏移
    const pdfRect = pdfElt.getBoundingClientRect()
    const scrollTop = pdfElt.scrollTop || 0
    const scrollLeft = pdfElt.scrollLeft || 0
    
    // 计算相对于PDF的位置（考虑滚动偏移）
    const posx = upEvent.clientX - pdfRect.left - sealSize.width / 2 + scrollLeft
    const posy = upEvent.clientY - pdfRect.top - sealSize.height / 2 + scrollTop
    
    // 计算当前页码（基于实际内容位置）
    const page = Math.floor(posy / 842) + 1  // 假设每页高度为842px（A4标准）
    
    // 计算页内位置
    const pagePosy = posy % 842
    
    // 创建签章信息
    const signInfo = {
      siteId: generateUUID(),
      page,
      posx,
      posy: pagePosy,
      width: sealSize.width,
      height: sealSize.height,
      signMethod,
      signSubjectId: person.id,
      showSignature: person.showSignature,
      showDate: person.showDate
    }
    
    // 移除临时元素
    document.body.removeChild(dragElt)
    
    // 添加到签章列表
    signs.push(signInfo)
    
    // 回调函数
    if (callback) {
      callback(signInfo)
    }
  }
  
  // 添加事件监听
  document.addEventListener('mousemove', handleMove)
  document.addEventListener('mouseup', handleUp)
}